﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace MediaCenterCommander.Code
{
    public class MediaCenterActionQueue
    {
        private object syncObject = new Object();
        private ManualResetEvent resetEvent;
        private Queue<MediaCenterAction> actionQueue;

        public MediaCenterActionQueue()
        {
            this.actionQueue = new Queue<MediaCenterAction>();
            this.resetEvent = new ManualResetEvent(false);
        }

        public void Add(MediaCenterAction action)
        {
            lock (this.syncObject)
            {
                this.actionQueue.Enqueue(action);
                this.resetEvent.Set();
            }
        }

        public MediaCenterAction WaitForNextAction()
        {
            for (; ; )
            {
                lock (this.syncObject)
                {
                    if (this.actionQueue.Count > 0)
                    {
                        var action = this.actionQueue.Dequeue();
                        return action;
                    }
                }

                this.resetEvent.WaitOne(5000);
            }
        }
    }

    public delegate void MediaCenterAction();
}
